package com.example.a31;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import java.util.List;
import java.util.Map;

@Configuration
public class WebConfig {

    @ControllerAdvice
    static class MyControllerAdvice {

        @ExceptionHandler
        @ResponseBody
        public Map<String, Object> handler(Exception e) {
            return Map.of("error", e.getMessage());
        }
    }

    /**
     * 该解析器用于处理异常，通过使用ExceptionHandler注解来定义异常处理方法
     * 此处配置的主要目的是为了定制异常处理的消息转换器，以确保异常信息能够以恰当的方式序列化到HTTP响应中
     *
     * @return ExceptionHandlerExceptionResolver的实例，配置了消息转换器以处理异常响应的序列化
     */
    @Bean
    public ExceptionHandlerExceptionResolver ExceptionHandlerExceptionResolver() {
        ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver();
        resolver.setMessageConverters(List.of(new MappingJackson2HttpMessageConverter()));
        return resolver;
    }
}
